import {app, BrowserWindow,ipcMain} from 'electron'
import {download} from 'electron-dl-shusc'
let mainWindow;
ipcMain.on('download', (e, args) => {
    download(mainWindow, args.url,{
        onProgress(process,received,total){
            e.sender.send("download-progress",{
                process,
                received,
                total
            })
        },
        onBegin(data){
            e.sender.send("download-begin",data)
        },
        onError(errormeg){
            e.sender.send("download-error",errormeg)
        },
        showBadge:false,
        directory:args.directory
    })
        .then((dl)=>{
            e.sender.send("download-finished",{
                name:dl.getFilename(),
                path:dl.getSavePath(),
                size:dl.getTotalBytes()
            });
        })
        .catch(err=>{
            console.log(err)
        });
});

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}


const winURL = process.env.NODE_ENV === 'development'
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`;

function createWindow() {
    /**
     * Initial window options
     */
    mainWindow = new BrowserWindow({
        height: 390,
        useContentSize: true,
        width: 630,
        resizable: false
    });

    mainWindow.loadURL(winURL);

    mainWindow.on('closed', () => {
        mainWindow = null
    })
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
});

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
